package com.tul.vapp.servicecenter.util;

import java.security.SecureRandom;
import java.util.Date;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;

import com.tul.cusa.common.util.DateUtil;

/**
 * 获取唯一键,此类参照携程apollo编写
 */
public class UniqueKeyGenerator {

	private static AtomicInteger counter = new AtomicInteger(new SecureRandom().nextInt());

	/**
	 * 根据入参生成唯一Key
	 * 
	 * @param args appId, namespace etc.
	 * @return 唯一Key
	 */
	public static String generate(Object... args) {
		String hexIdString = ByteUtil.toHexString(
				toByteArray(Objects.hash(args), MachineUtil.getMachineIdentifier(), counter.incrementAndGet()));

		return DateUtil.format(new Date(), "yyyyMMddHHmmss") + "-" + hexIdString;

	}

	/**
	 * Concat machine id, counter and key to byte array Only retrieve lower 3
	 * bytes of the id and counter and 2 bytes of the keyHashCode
	 * 
	 * @param keyHashCode key的hash code
	 * @param machineIdentifier 机器号
	 * @param count 随机数
	 * @return byte array
	 */
	protected static byte[] toByteArray(int keyHashCode, int machineIdentifier, int count) {
		byte[] bytes = new byte[8];
		bytes[0] = ByteUtil.int1(keyHashCode);
		bytes[1] = ByteUtil.int0(keyHashCode);
		bytes[2] = ByteUtil.int2(machineIdentifier);
		bytes[3] = ByteUtil.int1(machineIdentifier);
		bytes[4] = ByteUtil.int0(machineIdentifier);
		bytes[5] = ByteUtil.int2(count);
		bytes[6] = ByteUtil.int1(count);
		bytes[7] = ByteUtil.int0(count);
		return bytes;
	}

}
